package com.hyt.it.ogt.kq.service.gov.service.impl;

import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.common.gov.constant.CodeEnum;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.service.gov.feign.tps.GovTpsClient;
import com.hyt.it.ogt.kq.service.gov.mapper.OfficeCandidateTicketTemplateMapper;
import com.hyt.it.ogt.kq.service.gov.model.entity.OfficeCandidateTicketTemplate;
import com.hyt.it.ogt.kq.service.gov.model.vo.obs.HuaweiObsCopyObjectResultVO;
import com.hyt.it.ogt.kq.service.gov.service.IOfficeCandidateTicketTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 准考证模板表 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-08-28
 */
@Slf4j
@Service
public class OfficeCandidateTicketTemplateServiceImpl extends BaseServiceImpl<OfficeCandidateTicketTemplateMapper, OfficeCandidateTicketTemplate> implements IOfficeCandidateTicketTemplateService {

    @Resource
    private GovTpsClient tpsClient;

    @Resource
    private ConfigManager configManager;

    /**
     * 路径统一分隔符
     */
    public static final String SEPARATOR = "/";

    /**
     * 默认模板
     */
    private static final String TEMPLATED_EFAULT = "admissionTemplateSecurity.pdf";



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initOfficeTicketTemplate(String officeId) throws Exception {

        Integer count = lambdaQuery()
                .eq(OfficeCandidateTicketTemplate::getOfficeId,officeId)
                .eq(OfficeCandidateTicketTemplate::getDelFlag,false)
                .count();

        if (count > 0) {
            return;
        }

        //:初始化机构准考证模板


//        String templatePath = "templates/ticket/";
//        String suf = "*.pdf";
//
//        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        Resource[] resources = resolver.getResources(StringUtils.join(templatePath,suf));
//        List<OfficeCandidateTicketTemplate> list = new ArrayList<>();
//        for (int i = 0; i < resources.length; i++) {
//            String fileName = resources[i].getFilename();
//            log.info("准考证模板：{}",fileName);
//            OfficeCandidateTicketTemplate officeCandidateTicketTemplate = new OfficeCandidateTicketTemplate();
//            officeCandidateTicketTemplate.setOfficeId(officeId)
//                    .setChecked(CodeEnum.TEMPLATE_CHECKED_0.getCode())
//                    .setName(fileName)
//                    .setPath(StringUtils.join("/",templatePath,fileName))
//                    .setOfficeId(officeId)
//                    .setDelFlag(false)
//                    .setId(UUIDUtils.newSortUUID());
//            if(fileName.contains(TEMPLATED_EFAULT)){
//                officeCandidateTicketTemplate.setChecked(CodeEnum.TEMPLATE_CHECKED_1.getCode());
//            }
//            list.add(officeCandidateTicketTemplate);
//        }
//
//        saveBatch(list);
    }

    @Override
    public List<OfficeCandidateTicketTemplate> listByOfficeId(String officeId) {
        return this.lambdaQuery()
                .eq(OfficeCandidateTicketTemplate::getOfficeId, officeId)
                .eq(OfficeCandidateTicketTemplate::getLevel, CodeEnum.OFFICE_DATA.getCode())
                .eq(OfficeCandidateTicketTemplate::getDelFlag, false)
                .list();
    }

    @Override
    public List<OfficeCandidateTicketTemplate> init(String officeId) {
        //机构下暂无准考证模板数据，获取系统准考证模板数据
        List<OfficeCandidateTicketTemplate> systemCandidateTicketTemplateList = this.listBySystem();
        //复制系统准考证模板数据，作为机构准考证模板数据
        return systemCandidateTicketTemplateList.stream().map(system -> {
            //获取系统级模板路径
            String officeCandidateTicketTemplatePath = this.getOfficeCandidateTicketPath(officeId, system.getName());
            ApiResponse<HuaweiObsCopyObjectResultVO> response = tpsClient.copyHuaweiObsObject(officeId, system.getPath(),
                    officeCandidateTicketTemplatePath);
            HuaweiObsCopyObjectResultVO huaweiObsCopyObjectResultVO = response.getData();
            int statusCode = Optional.ofNullable(huaweiObsCopyObjectResultVO)
                    .map(HuaweiObsCopyObjectResultVO::getStatusCode)
                    .orElse(0);
            if (response.getCode() != 1
                    || statusCode != HttpServletResponse.SC_OK) {
                throw new KqException(ResponseCode.TASK_INIT_FAIL.getCode(),
                        "复制系统准考证模板数据至机构中失败");
            }
            //将复制后的系统级准考证模板数据保存至机构中
            OfficeCandidateTicketTemplate officeCandidateTicketTemplate = new OfficeCandidateTicketTemplate();
            officeCandidateTicketTemplate.setLevel(CodeEnum.OFFICE_DATA.getCode())
                    .setOfficeId(officeId)
                    .setPath(officeCandidateTicketTemplatePath)
                    .setChecked(system.getChecked())
                    .setName(system.getName());
            if (!this.save(officeCandidateTicketTemplate)) {
                throw new KqException(ResponseCode.TASK_INIT_FAIL.getCode(),
                        "将系统级准考证模板数据保存至机构中时，插入系统、机构级准考证模板表失败");
            }
            return officeCandidateTicketTemplate;
        }).collect(Collectors.toList());
    }

    @Override
    public List<OfficeCandidateTicketTemplate> listBySystem() {
        return this.lambdaQuery()
                .eq(OfficeCandidateTicketTemplate::getLevel, CodeEnum.SYSTEM_DATA.getCode())
                .eq(OfficeCandidateTicketTemplate::getDelFlag, false)
                .list();
    }

    @Override
    public String getOfficeCandidateTicketPath(String officeId, String fileName) {
        //机构级模板文件存储规则：“根目录/模板文件存放目录名/机构级模板目录名/机构id/具体的文件.xxx”
        String cloudRootPath = configManager.getCloudRootPath();
        cloudRootPath = cloudRootPath.substring(0, cloudRootPath.length() - 1);
        return StringUtils.joinWith(SEPARATOR, cloudRootPath, configManager.getTemplatePath(),
                configManager.getOfficeTemplatePath(), officeId, fileName);

    }

}
